from django.shortcuts import render
from rest_framework import viewsets,status
from .models import Inform,InformRead
from .serializers import InformSerialize,ReadInformSerialize
from django.db.models import Q
from rest_framework.response import Response
from rest_framework.views import APIView
from django.db.models import Prefetch

# Create your views here.
class InformViewSet(viewsets.ModelViewSet):
    queryset = Inform.objects.all()
    serializer_class = InformSerialize

    # 通知列表
    # 1.inform.public = True  即选择了所有部门
    # 2.inform.departments 包含了当前用户所在部门
    # 3.inform.author = request.user

    # 也可以重写list方法
    def get_queryset(self):
        # 如果多个条件的并查 那么就需要用到Q函数
        # 这里的 = 有包含的意思
        # 筛选出能查看的通知
        # queryset = self.queryset.filter(Q(public = True) | Q(departments=self.request.user.department)| Q(author=self.request.user))
        # 如果queryset有很多条 那么也会从数据库中查询很多次 这样性能就很低
        # for inform in queryset:
        #     inform.is_read = InformRead.objects.filter(inform=inform,user=self.request.user).exists()
        # distinct() 去除多余数据
        #  以下这种情况 只会获取所有阅读过这个通知的人 而我们需要获取的是当前用户是否阅读过
        # 可以使用Prefetch函数 它可以在查询中完成筛选
        # queryset = self.queryset.select_related('author').prefetch_related("reads",'departments').filter(Q(public = True) | Q(departments=self.request.user.department)| Q(author=self.request.user)).distinct()
        queryset = self.queryset.select_related('author').prefetch_related(Prefetch("reads", queryset=InformRead.objects.filter(user_id=self.request.user.uid))).filter(
            Q(public=True) | Q(departments=self.request.user.department) | Q(author=self.request.user)).distinct()

        return queryset

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        # 这里的instace 是Inform对象
        # class 'apps.inform.models.Inform'>
        # print(type(instance))
        data['read_count'] = InformRead.objects.filter(inform_id=instance.id).count()
        return Response(data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.author.uid == request.user.uid:
            self.perform_destroy(instance)
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            return Response(status=status.HTTP_401_UNAUTHORIZED)


class InformReadView(APIView):
    def post(self,request):
        serialize = ReadInformSerialize(data=request.data)
        if serialize.is_valid():
            inform_pk = serialize.validated_data['inform_pk']
            # 看是否是第一次进入该详情页  也就是在informread表中查看是否存在该id
            if InformRead.objects.filter(inform_id=inform_pk,user_id=request.user.uid).exists():
                # 不需要告诉用户这一行为
                return Response()
            else:
                # 第一次进入详情页 把传入的id放到informread表中
                InformRead.objects.create(inform_id=inform_pk, user_id=request.user.uid)
                return Response()
        else:
            return Response(data={'detail': list(serialize.errors.values())[0][0]},status=status.HTTP_400_BAD_REQUEST)
